﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace InterlockStudy
{
    class ConcurrentIncrease
    {
        public static void Test()
        {
            var sum = 0;

            var tasks = new Task[10];
            for (var i = 1; i <= 10; i++)
            {
                tasks[i - 1] = Task.Factory.StartNew((state) =>
                {
                    int localSum, currentSum;
                    do
                    {
                        localSum = sum;

                        Thread.Sleep(10);
                        var value = (int)state;
                        var newValue = localSum + value;

                        currentSum = Interlocked.CompareExchange(ref sum, newValue, localSum);
                    } while (localSum != currentSum);
                }, i);
            }

            Task.WaitAll(tasks);

            Console.WriteLine(sum);
        }
    }
}
